using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace UnityGameFramework.Editor
{
    public abstract class ProloadScriptableObjectBuildProcessor<T> : IPreprocessBuildWithReport, IPostprocessBuildWithReport
        where T: PreloadRuntimeSettingScriptableObject<T>
    {
        public abstract int callbackOrder { get; }

        public virtual void OnPreprocessBuild(BuildReport report)
        {
            var sobj = PreloadRuntimeSettingScriptableObject<T>.SettingObject;
            if (sobj == null)
            {
                throw new FileNotFoundException($"Setting File for {typeof(T).FullName}");
            }

            RegistProload(sobj);
        }

        public virtual void OnPostprocessBuild(BuildReport report)
        {
            UnregistProload();
        }

        protected void RegistProload(T setting)
        {
            var allPreloads = PlayerSettings.GetPreloadedAssets();
            if (!allPreloads.Contains(setting))
            {
                var list = allPreloads.ToList();
                list.Add(setting);
                PlayerSettings.SetPreloadedAssets(list.ToArray());
            }
        }

        protected void RegistMany(T[] settings)
        {
            var allPreloads = PlayerSettings.GetPreloadedAssets().ToList();
            allPreloads.AddRange(settings.Where(s => !(allPreloads.Contains(s))));
            PlayerSettings.SetPreloadedAssets(allPreloads.ToArray());
        }

        protected void UnregistProload()
        {
            System.Type type = typeof(T);
            PlayerSettings.SetPreloadedAssets(PlayerSettings.GetPreloadedAssets().Where(s => (s != null || s.GetType() != type)).ToArray());
        }
    }
}
